<template>
  <view class="page-wrapper purchase-confirm-page page">
    <div class="page-title">订单确认 Order Confirm</div>
    <div class="wrap">
      <div class="goods-img">
        <img class="img" :src="ossDomain + proInfo.coverImg" mode="aspectFill" alt="" />
      </div>
      <div class="title">
        {{ proInfo.name }} <br />
        {{ proInfo.enName }}
      </div>
      <div class="te">{{ proInfo.sku.name }} {{ proInfo.sku.enName }}</div>
      <div class="te">x{{ proInfo.count }}</div>
      <div class="title" @click="toAddress">收件人信息 Recipient Information</div>
      <div class="te" v-if="address.name">
        {{ address.name }} {{ address.phone }}
        <br />
        {{ address.province + address.city + address.district + address.placeInfo }}
      </div>
      <div class="te" v-if="address.name">
        <div class="btn" @click="toAddress">更改 Change &#62;</div>
      </div>
      <div class="te">运费 Shipping</div>
      <!-- 运费 -->
      <div class="te">¥ {{ noFreightPrice < 199 ? 10 : 0 }}</div>
      <div class="title">积分抵扣 Redeem points</div>
      <div class="te integral-input-box">
        <div class="check-radio" :class="{ checked: useIntegral }" @click="useIntegral = true">
          <uv-icon v-if="useIntegral" class="radio-icon" name="checkmark-circle-fill" color="#fff"></uv-icon>
        </div>

        <div>¥ -{{ orderUseIntergral / 100 }} 积分</div>
        <input
          class="integral-input"
          type="number"
          :key="inputKey"
          v-model="orderUseIntergral"
          @blur="integralChange"
        />
        <div>Points({{ userInfo.integral }})</div>
      </div>
      <div class="te integral-input-box" @click="notUseIntegral">
        <div class="check-radio" :class="{ checked: !useIntegral }">
          <uv-icon v-if="!useIntegral" class="radio-icon" name="checkmark-circle-fill" color="#fff"></uv-icon>
        </div>
        <div>不使用 Do not use</div>
      </div>
    </div>
    <div class="bottom-control-box">
      <div class="bottom-control-container">
        <div class="wrap">
          <div class="left-box">
            <div class="div">
              ¥
              {{ lastPrice }}
            </div>
          </div>
          <div
            class="bottom-control-btn"
            :class="{ disabled: !loaded || info.skuVos.inventory === 0 }"
            @click="confirmPurchase"
          >
            确认 Confirm
          </div>
        </div>
        <bottom-safe-area></bottom-safe-area>
      </div>
      <div>
        <div style="height: 100rpx"></div>
        <bottom-safe-area></bottom-safe-area>
      </div>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch, computed, nextTick } from 'vue'
import { useStore } from 'vuex'

import { ossDomain } from '@/utils/oss'
const store = useStore()

import { onLoad, onShow } from '@dcloudio/uni-app'

import { clientUserInfo } from '@/utils/api/user'

import { saveOrder, payOrder } from '@/utils/api/order'

import { defaultAddress } from '@/utils/api/address'

import { roundNumber } from '@/utils/reg'
import { round } from '@/uni_modules/uv-ui-tools/libs/function/digit'
//
let userInfo = computed(() => {
  return store.state.user.userInfo
})
console.log('用户信息----', userInfo.value)
// 商品信息
let proInfo = ref<any>({})
// 收货地址
let address = ref<any>({})
// 是否使用积分
let useIntegral = ref<boolean>(true)
// 最后使用的积分
const lastIntegral = computed(() => {
  let integral = userInfo.value.integral * 1
  return roundNumber(integral > isVipPrice.value * 100 ? isVipPrice.value * 100 : integral, 2)
})

let vip = computed(() => {
  return store.getters['user/isVip']
})
// 是否是vip的价格
let isVipPrice = computed(() => {
  return roundNumber(
    vip.value ? proInfo.value.price * proInfo.value.count * 0.9 : proInfo.value.price * proInfo.value.count,
    2
  )
})

// 未计算运费的价格
let noFreightPrice = computed(() => {
  let price = vip.value ? proInfo.value.price * proInfo.value.count * 0.9 : proInfo.value.price * proInfo.value.count
  let integral = useIntegral.value ? lastIntegral.value : 0
  return roundNumber(price - integral / 100, 2)
})
// 最zhong的价格
let lastPrice = computed(() => {
  // 判断是不是vip
  let price = vip.value ? proInfo.value.price * proInfo.value.count * 0.9 : proInfo.value.price * proInfo.value.count
  // 判断是否使用积分
  let integral = useIntegral.value ? lastIntegral.value : 0
  // 没有使用运费的费用
  let noFrePrice = price - integral / 100
  // 运费
  let frePrice = noFrePrice < 199 ? 10 : 0
  // 返回最终价格
  return roundNumber(price - integral / 100 + frePrice, 2)
})

let isLoad: boolean = false
let maxIntergral = computed(() => {
  let integral = userInfo.value.integral * 1
  return roundNumber(integral > isVipPrice.value * 100 ? isVipPrice.value * 100 : integral, 2)
})

let orderUseIntergral = ref<string>('')
// 获取个人信息
onLoad(async (options) => {
  console.log('携带来的参数', options)
  proInfo.value = JSON.parse(options.opt)
  isLoad = true
  store.dispatch('user/getUserInfo').then(() => {
    console.log('获取用户信息成功')
    orderUseIntergral.value = maxIntergral.value
  })
  const addrInfo = await defaultAddress()
  if (addrInfo.code == 200) {
    address.value = addrInfo.data
  }
})

onShow(() => {
  if (isLoad) {
    isLoad = false
  } else {
    let addInfo = uni.getStorageSync('checkedAddress')
    console.log('缓存地址信息', addInfo)
    address.value = addInfo ? addInfo : {}
    if (addInfo) {
      uni.removeStorageSync('checkedAddress')
    }
  }
})
const toAddress = () => {
  uni.navigateTo({
    url: '/pages/address/address'
  })
}

const inputKey = ref(0)
const integralChange = (e: any) => {
  if (e.detail.value > maxIntergral.value) {
    orderUseIntergral.value = maxIntergral.value
    inputKey.value++ // 强制刷新 input
    console.log('超出最大积分', orderUseIntergral.value)
  } else {
    orderUseIntergral.value = e.detail.value
  }
}
const integralCalc = (integral: number) => {
  let num = 0
  if (integral > 100) {
    num = Math.floor(integral / 100)
  }
  return num
}

const notUseIntegral = () => {
  console.log('不使用积分')
  useIntegral.value = false
}

interface Params {
  index: number
  tabIndex: number
}

let params: Params = {
  index: 3,
  tabIndex: 2
}

const confirmPurchase = async () => {
  console.log('确认购买生成订单')
  if (!address.value.id) {
    console.log('地址信息', address.value)
    uni.showModal({
      title: '提示',
      content: '请选择收货地址',
      showCancel: false
    })
    return
  }
  let obj = {}
  const skuId = proInfo.value.sku.id
  const count = Number(proInfo.value.count)
  const integral = useIntegral.value ? Number(orderUseIntergral.value) : 0
  obj.integral = integral
  obj.objectId = proInfo.value.id
  obj.quantity = count
  obj.skuId = skuId
  obj.type = 2
  const orderRes = await saveOrder(obj)
  if (orderRes.code == 200) {
    const payRes = await payOrder({
      orderId: orderRes.data.orderId,
      payType: 1,
      userAddressId: address.value.id
    })
    // 支付以后跳转用的页面参数

    if (payRes.code == 200) {
      let data = JSON.parse(payRes.data)
      wx.requestPayment({
        timeStamp: data.timestamp, //时间戳
        nonceStr: data.noncestr, //随机字符串
        package: data.package, //prepay_id
        signType: data.signType, //签名算法MD5
        paySign: data.paySign, //签名'
        success(res) {
          if (res.errMsg == 'requestPayment:ok') {
            console.log('支付成功', res)

            uni.reLaunch({
              url: `/pages/index/index?params=${JSON.stringify(params)}`
            })
          } else {
            setTimeout(() => {
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              })
            }, 100)
            uni.reLaunch({
              url: `/pages/index/index?params=${JSON.stringify(params)}`
            })
          }
        },
        fail(res) {
          setTimeout(() => {
            uni.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }, 100)
          uni.reLaunch({
            url: `/pages/index/index?params=${JSON.stringify(params)}`
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './purchaseConfirm.scss';
</style>
